package com.yihr.controller;

import com.yihr.ApiResponse;
import com.yihr.aop.security.SecurityInterface;
import com.yihr.bean.User;
import com.yihr.bean.valid.UserLoginInterface;
import com.yihr.bean.valid.UserRegisterInterface;
import com.yihr.service.account.AccountService;
import com.yihr.util.EncryptUtil;
import com.yihr.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/apiv1/user", "/ajax/apiv1/user"})
//@CrossOrigin
public class UserController {

    @Autowired
    AccountService accountService;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public ApiResponse test() {
        return new ApiResponse().success();
    }

    @RequestMapping(value = "/tt", method = RequestMethod.GET)
    public ApiResponse testTime(HttpServletRequest httpServletRequest) {

        System.out.println("testTime:" + httpServletRequest.getRequestURI());

        System.out.println(this.getClass().toString());

        return new ApiResponse().success(new Date());
    }

    @RequestMapping(value = "/un", method = RequestMethod.GET)
    public ApiResponse testUn() throws Exception {
        throw new Exception("Exception test");
    }

    // 火狐restclient测试会有问题
//    @RequestMapping(value = "/param", method = RequestMethod.GET)
    @RequestMapping(value = "/param", method = RequestMethod.POST, consumes = "application/json")
//    @RequestMapping(value = "/param")
    public ApiResponse testUn(@RequestParam String user) throws Exception {
        return new ApiResponse().success(user);
    }

//    @requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容，
//   比如说：application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。

    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResponse createAdvertiser(@RequestBody @Valid User loginParam) {
        System.out.println(loginParam+"--");
        return new ApiResponse().success(loginParam.toString());
    }

    //    public ApiResponse createAdvertiser(@Email @RequestParam String email,
//                                        @Size(min = 32, max = 32) @RequestParam String password) {
    @RequestMapping(value = "/loginemail", method = RequestMethod.POST)
    public ApiResponse createAdvertiser(@RequestParam("email") String email) {
//        System.out.println(email +" -- " + password);
        System.out.println(email);
        return new ApiResponse().success(email);
    }

    //////////////////



    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
    public ApiResponse register(@RequestBody @Validated(value = {UserRegisterInterface.class}) User user) {
        long usernameAndEmail = accountService.checkUsernameAndEmail(user.getUsername(), user.getEmail());
        if (usernameAndEmail > 0) {
            throw new RuntimeException("用户名或邮箱已注册");
        }

        accountService.insertUser(user);
        User userById = accountService.getUserById(user.getId());
        return new ApiResponse().success(userById).jwt(JwtUtil.createJwt(userById));
    }

    // 登陆时密码采用MD5值
    @RequestMapping(value = "/loginuser", method = RequestMethod.POST, consumes = "application/json")
    public ApiResponse login(@RequestBody @Validated(value = {UserLoginInterface.class}) User user) {
        Map<String, Object> loginInfoMap = accountService.getLoginInfoByUsername(user.getUsername());
        if (null == loginInfoMap ||
                !(loginInfoMap.containsKey("password") && loginInfoMap.containsKey("salt") && loginInfoMap.containsKey("id"))) {
            throw new RuntimeException("用户名错误");
        }

        String pw = (String) loginInfoMap.get("password");
        String salt = (String) loginInfoMap.get("salt");
        // id 类型为 java.math.BigInteger
        long id = Long.parseLong(loginInfoMap.get("id").toString());
        if (!pw.equals(EncryptUtil.String2SHA256(user.getPassword().toUpperCase() + salt))) {
            throw new RuntimeException("密码错误");
        }

        User userById = accountService.getUserById(id);
        return new ApiResponse().success(userById).jwt(JwtUtil.createJwt(userById));
    }

    @SecurityInterface
    @RequestMapping(value = "/userinfo/{id}", consumes = "application/json")
    public ApiResponse userinfo(@PathVariable("id") long id) {

        User userById = accountService.getUserById(id);
        return new ApiResponse().success(userById);
    }

    // 用于用户信息变更后，主动刷新jwt，jwt在date上
    @SecurityInterface
    @RequestMapping(value = "/userinfo/{id}/jwt", consumes = "application/json")
    public ApiResponse userUpdateJwt(@PathVariable("id") long id) {
        User userById = accountService.getUserById(id);
        return new ApiResponse().success(JwtUtil.createJwt(userById));
    }

    @SecurityInterface(role = "admin")
    @RequestMapping(value = "/userinfo/{id}/all", consumes = "application/json")
    public ApiResponse userAll(@PathVariable("id") long id) {
        long countUser = accountService.countUser(null);

        List<User> userFP = accountService.getUserFP(null, 0, countUser);
        return new ApiResponse().success(userFP);
    }

}
